package de.dopichaj.labrador.index.backend;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;

import de.dopichaj.labrador.util.io.BitInputStream;
import de.dopichaj.labrador.util.io.BufferedDataInputFromRandomAccessFile;


public final class DiskDictionary implements ReadOnlyDictionary {
    
    private static final Logger log = Logger.getLogger(DiskDictionary.class);

    private static final class TermPosition implements Comparable<TermPosition> {
        private final String termString;
        private final long position;
        
        public TermPosition(final String termString, final long position) {
            this.termString = termString;
            this.position = position;
        }

        public int compareTo(TermPosition o) {
            return termString.compareTo(o.termString);
        }
    }
    
    private final List<TermPosition> positions = new ArrayList<TermPosition>();
    private final RandomAccessFile file;
    
    public DiskDictionary(final RandomAccessFile file) throws IOException {

        this.file = file;
        file.seek(0);
        final BitInputStream input = new BitInputStream(new BufferedDataInputFromRandomAccessFile(file, 0, Long.MAX_VALUE)); 
        final int count = input.readVariableLengthInt();
        for (int i = 0; i < count; i++) {
            
            final long startPos;
            if (i % Dictionary.BLOCK_SIZE == 0) {
                input.skipToNext();
                startPos = input.getPosition();
            } else {
                startPos = 0;
            }
            
            final String text = readTerm(input).getText();
            if (i % Dictionary.BLOCK_SIZE == 0) {
                positions.add(new TermPosition(text, startPos));
            }
        }

    }

    /**
     * @param input
     * @return
     * @throws IOException
     */
    private Term readTerm(final BitInputStream input) throws IOException {
        
        final int termID = input.readVariableLengthInt();
        final String text = input.readString();
        final int elementFrequency = input.readVariableLengthInt();
        final int documentFrequency = input.readVariableLengthInt();
        final int collectionFrequency = input.readVariableLengthInt();
        final int indexPos = input.readBits(31);
        final Term term = new Term(termID, text, elementFrequency, documentFrequency, collectionFrequency);
        term.setIndexPosition(indexPos);
        return term;
    }
    
    public Term getTerm(String termString) {
        
        // seek to the start position of the corresponding block
        int pos = Collections.binarySearch(positions, new TermPosition(termString, 0));
        if (pos < 0) {
            pos = -(pos + 1) - 1;
            if (pos < 0) {
                pos = 0;
            }
        }
        final BitInputStream input =
            new BitInputStream(
                new BufferedDataInputFromRandomAccessFile(file,
                    positions.get(pos).position, Long.MAX_VALUE));
        // compare each term in the block with the string
        for (int i = 0; i < Dictionary.BLOCK_SIZE; i++) {
            
            Term term;
            try {
                term = readTerm(input);
            } catch (IOException e) {
                log.error("Error reading entry for term " + termString);
                return null;
            }
            if (term.getText().equals(termString)) {
                return term;
            }
        }
        
        // if nothing was found, return null
        return null;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/